/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.knoppers.examples;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 *
 */
public class FileUploadAction extends org.apache.struts.action.Action {

	/* forward name="success" path="" */
	private final static String SUCCESS = "success";

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
	 * ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		final FileUploadForm uploadForm = (FileUploadForm) form;
		FileOutputStream outputStream = null;
		FormFile formFile = null;

		try {

			formFile = uploadForm.getFile();
			outputStream = new FileOutputStream(getFile(formFile));
			outputStream.write(formFile.getFileData());

		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}

		uploadForm.setMessage("The file " + formFile.getFileName()
				+ " is uploaded successfully.");

		return mapping.findForward(SUCCESS);
	}

	/**
	 * @param formFile
	 * @return
	 */
	private File getFile(FormFile formFile) {
		return new File(getPath(formFile));
	}

	/**
	 * @param formFile
	 * @return
	 */
	private String getPath(FormFile formFile) {
		return getServlet().getServletContext().getRealPath("") + "/"
				+ formFile.getFileName();
	}
}
